<?php

declare(strict_types=1);

namespace App\Common\Robot;

use App\Common\Robot\Contracts\GatewayInterface;
use App\CustHub\Mapper\ChServerMapper;
use InvalidArgumentException;
use RuntimeException;

class Robot
{
    protected $gateways = [];

    protected $defaultGateway = 'easyWeWork';

    protected string $name;

    public function __construct(protected int $serverId,protected string $uuid)
    {
        $serverInfo = container()->get(ChServerMapper::class)->findById($serverId);
        $this->name = !empty($serverInfo->gateway) ? $serverInfo->gateway : $this->getDefaultGateway();
    }

    /**
     * 网关
     * @param $name
     * @return GatewayInterface|mixed
     */
    public function gateway(): mixed
    {
        $name = $this->name;

        if (!isset($this->gateways[$name])) {
            $this->gateways[$name] = $this->createGateway($name);
        }

        return $this->gateways[$name];
    }

    private function getDefaultGateway()
    {

        if (empty($this->defaultGateway)) {
            throw new RuntimeException('No default gateway configured.');
        }

        return $this->defaultGateway;
    }

    /**
     * 创建网关
     *
     * @param $name
     * @return GatewayInterface
     */
    protected function createGateway($name)
    {
        $className = $this->formatGatewayClassName($name);

        $gateway = $this->makeGateway($className);

        if (!($gateway instanceof GatewayInterface)) {
            throw new InvalidArgumentException(\sprintf('Gateway "%s" must implement interface %s.', $name, GatewayInterface::class));
        }

        return $gateway;
    }

    /**
     * 格式网关类名
     *
     * @param $name
     * @return string
     */
    protected function formatGatewayClassName($name): string
    {
        if (\class_exists($name) && \in_array(GatewayInterface::class, \class_implements($name))) {
            return $name;
        }

        $name = \ucfirst(\str_replace(['-', '_', ''], '', $name));

        return __NAMESPACE__."\\Gateways\\{$name}Gateway";
    }

    /**
     * 制作网关
     *
     * @param $gateway
     * @return mixed
     */
    protected function makeGateway($gateway): mixed
    {
        if (!\class_exists($gateway) || !\in_array(GatewayInterface::class, \class_implements($gateway))) {
            throw new InvalidArgumentException(\sprintf('Class "%s" is a invalid easy-sms gateway.', $gateway));
        }

        return make($gateway,[$this->serverId,$this->uuid]);
    }
}